package com.nc.delivery_project.client.order_details;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.CargoRequest;
import com.nc.delivery_project.client.request.OrderRequest;
import com.nc.delivery_project.shared.proxy.CargoProxy;
import com.nc.delivery_project.shared.proxy.OrderProxy;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Natalie D.
 * Date: 1/26/15
 * Time: 9:43 PM
 */
public class OrderDetailsActivity extends AbstractActivity implements OrderDetailsPresenter{


    private OrderDetailsView view;

    private ClientFactory clientFactory;

    private OrderProxy order;

    private int orderId;

    private List<CargoProxy> cargoes;

    private OrderRequest updateRequest;

    private int fetchedCount;

    public OrderDetailsActivity(OrderDetailsPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        parseToken(place.getToken());
        updateRequest = clientFactory.getRequestFactory().createOrderRequest();
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {



        if (view == null) {
            view = new OrderDetailsView();
        }

        view.setPresenter(this);
        panel.setWidget(view);
        view.start();

      //  view.orderIdLbl.setText(String.valueOf(orderId));

        initButtonHandlers();

        fetchOrder(orderId);
        loadCargoes(orderId);
    }

    @Override
    public void loadOrderDetails(OrderProxy order) {
        view.orderIdLbl.setText(String.valueOf(orderId));
        view.senderLbl.setText(order.getSender().getEmail());
        view.receiverLbl.setText(order.getReceiver().getEmail());
        view.commentTxtBox.setText(order.getComment());
        view.paymentLbl.setText(order.getPayment().getAmount().toString());
        view.startDateTxtBox.setText(order.getStartDate());
        view.deliveryDateTxtBox.setText(order.getDeliveryDate());
        view.statusTxtBox.setText(order.getStatus());
    }

    @Override
    public void loadCargoes(int id) {
        final CargoRequest cargoRequest = clientFactory.getRequestFactory().createCargoRequest();

        cargoRequest.readByOrderId(id).fire(new Receiver<List<CargoProxy>>() {
            @Override
            public void onSuccess(List<CargoProxy> response) {
                GWT.log("cargoes fetched");
                cargoes = response;
                if (++fetchedCount == 2) fillView();
                }

            @Override
            public void onFailure(ServerFailure error) {
                //super.onFailure(error);
                // GWT.log(error.toString());
                GWT.log("fail load cargoes");
            }
        });
    }
    @Override
    public void update(OrderProxy order) {
        updateRequest.update(order).fire();
        Window.Location.reload();
    }

    @Override
    public void delete(int orderId) {
        clientFactory.getRequestFactory().createOrderRequest().delete(orderId).fire();
    }


    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }

    private void initButtonHandlers() {
        view.saveOBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                order.setComment(view.commentTxtBox.getText());
                order.setStartDate(view.startDateTxtBox.getText());
                order.setStatus(view.statusTxtBox.getText());
                order.setDeliveryDate(view.deliveryDateTxtBox.getText());
                //user.setRole(roles.get(view.roleLstBox.getSelectedIndex()));
              //  GWT.log("before update\n"+order.getId()+"\n "+order.getStartDate()+"\n"+order.getDeliveryDate()
                //+"\n"+ order.getComment() +"\n"+ order.getSender().getId()+"\n"+order.getReceiver().getId()+"\n"+ order.getStatus());

                update(order);
            }
        });

        view.removeOBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                delete(order.getId());
            }
        });


    }



    private void fetchOrder(int id) {
        OrderRequest orderRequest = clientFactory.getRequestFactory().createOrderRequest();
        orderRequest.read(id).with("sender").with("receiver").with("payment").fire(new Receiver<OrderProxy>() {
            @Override
            public void onSuccess(OrderProxy response) {
                GWT.log("order fetched");
                order = updateRequest.edit(response);
               // order=response;

                if (++fetchedCount == 2) fillView();
            }
            @Override
        public void onFailure(ServerFailure e)
            {

                GWT.log("fail fetch order");
            }
        });
    }

    private void fillView() {
       // loadCargoes();
        loadOrderDetails(order);
        view.setDataList(cargoes);
    }

    private void parseToken(String token) {
        try {
            orderId = Integer.parseInt(token);
        } catch (NumberFormatException e) {
            Window.alert("Unknown Token");
        }
    }

}